<!--
  * CEP规则表单
  *
  * @Author:    chenyuqiang
  * @Date:      2025-08-21 22:46:37
  * @Copyright  1
-->
<template>
  <a-modal
      :title="formData.id ? '编辑CEP规则' : '新增CEP规则'"
      :width="1000"
      :open="visible"
      :confirm-loading="submitLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      destroyOnClose
      :maskClosable="false"
  >
    <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
    >
      <!-- 基本信息 -->
      <a-divider orientation="left">基本信息</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="规则名称" name="ruleName">
            <a-input
                v-model:value.trim="formData.ruleName"
                placeholder="请输入规则名称"
                :maxlength="100"
                show-count
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="规则编码" name="ruleCode">
            <a-input
                v-model:value.trim="formData.ruleCode"
                placeholder="请输入规则编码"
                :maxlength="50"
                show-count
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="规则类型" name="ruleType">
            <a-select
                v-model:value="formData.ruleType"
                placeholder="请选择规则类型"
                allow-clear
            >

              <a-select-option value="SIMPLE">普通规则</a-select-option>
              <a-select-option value="COMPLEX">关联规则</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="优先级" name="priority">
            <a-input-number
                v-model:value="formData.priority"
                placeholder="请输入优先级"
                :min="1"
                style="width: 100%"
            />
            <template #extra>
              <span class="form-tip">数字越大优先级越高</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="规则状态" name="status">
            <a-select
                v-model:value="formData.status"
                placeholder="请选择规则状态"
            >
              <a-select-option value="ACTIVE">激活</a-select-option>
              <a-select-option value="INACTIVE">停用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="规则版本" name="version">
            <a-input
                v-model:value.trim="formData.version"
                placeholder="请输入版本号"
                :maxlength="20"
            />
            <template #extra>
              <span class="form-tip">规则发生变化时版本号要跟随更新</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="规则描述" name="ruleDescription">
        <a-textarea
            v-model:value.trim="formData.ruleDescription"
            placeholder="请输入规则描述"
            :rows="3"
            :maxlength="500"
            show-count
        />
      </a-form-item>

      <!-- CEP配置 -->
      <a-divider orientation="left">CEP配置</a-divider>

      <!-- 在EPL表单项位置添加新的实现 -->
      <a-form-item label="规则语句(EPL)" name="epl">
        <div class="epl-editor">
          <a-textarea
              ref="eplInputRef"
              v-model:value="formData.epl"
              placeholder="请输入CEP规则语句"
              :rows="6"
              show-count
              @input="handleEplInput"
              @blur="validateEplSyntax"
              :status="eplValidateStatus"
          />
          <!-- 智能提示下拉框 -->
          <div v-if="showSuggestions" class="epl-suggestions" :style="suggestionStyle">
            <div
                v-for="(item, index) in filteredSuggestions"
                :key="index"
                class="suggestion-item"
                :class="{ active: currentSuggestionIndex === index }"
                @click="selectSuggestion(item)"
            >
              <template v-if="item.type === 'field'">
                <span class="suggestion-label">{{ item.label }}</span>
                <span class="suggestion-type">字段</span>
              </template>
              <template v-else-if="item.type === 'operator'">
                <span class="suggestion-label">{{ item.label }}</span>
                <span class="suggestion-type">运算符</span>
              </template>
            </div>
          </div>
        </div>
        <template #extra>
          <span :class="['form-tip', eplValidateStatus === 'error' ? 'error-tip' : eplValidateStatus === 'success' ? 'success-tip' : '']">
            {{ eplValidateMessage || '支持EPL语法，请确保语法正确' }}
          </span>
        </template>
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="7">
          <a-form-item label="窗口大小" name="windowSize">
            <a-input-number
                v-model:value="formData.windowSize"
                placeholder="请输入窗口大小"
                :min="0"
                :precision="2"
                style="width: 80%"
            />
            <template #extra>
              <span class="form-tip">默认秒，建议值：1-3600</span>
            </template>
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="窗口滑动" name="windowSlide">
            <a-input-number
                v-model:value="formData.windowSlide"
                placeholder="请输入窗口滑动"
                :min="0"
                :precision="2"
                style="width: 80%"
            />
            <template #extra>
              <span class="form-tip">默认秒，建议值：1-3600</span>
            </template>
          </a-form-item>
        </a-col>
        <a-col :span="10">
                  <a-form-item label="分组字段" name="groups">
          <a-select
            v-model:value="formData.groups"
            mode="multiple"
            placeholder="请选择分组字段"
            :options="fieldOptions"
            :max-tag-count="3"
            :max-tag-text-length="10"
            allow-clear
            show-search
            :filter-option="filterOption"
            style="width: 100%"
          />
        </a-form-item>
        </a-col>
      </a-row>

      <!-- 高级配置 -->
      <a-divider orientation="left">高级配置</a-divider>

      <!-- 修改ruleCepStepList配置部分 -->
      <!-- <a-form-item label="告警条件111" name="ruleCepStepList" style="margin-left: 0%;"> -->
        <div v-for="(step, index) in formData.ruleCepStepList" :key="index" class="step-item">
          <a-row :gutter="16">
            <a-col :span="15">
              <a-form-item
                  :name="['ruleCepStepList', index, 'stepName']"
                  :rules="[{ required: true, message: '请选择字段' }]"
                  label="字段名称"
              >
                <a-select
                    v-model:value="step.stepName"
                    placeholder="请选择字段"
                    :options="fieldOptions"
                    show-search
                    :filter-option="(input, option) =>
                    option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
                />
              </a-form-item>
            </a-col>
            <a-col :span="15">
              <a-form-item
                  :name="['ruleCepStepList', index, 'eventType']"
                  :rules="[{ required: true, message: '请选择条件类型' }]"
                  label="条件类型"
              >
                <a-select
                    v-model:value="step.eventType"
                    placeholder="请选择条件类型"
                    :options="conditionTypes"
                />
              </a-form-item>
            </a-col>
            <a-col :span="15">
              <template v-if="step.eventType === 'STATIC'">
                <a-form-item
                    :name="['ruleCepStepList', index, 'tvalue']"
                    :rules="[{ required: true, message: '请输入值' }]"
                    label="静态值"
                >
                  <a-input
                      v-model:value="step.tvalue"
                      placeholder="请输入静态值"
                  />
                </a-form-item>
              </template>

              <template v-else-if="step.eventType === 'EXPRESSION'">
                <div class="expression-container">
                  <!-- if-else if-else 结构 -->
                  <div class="if-else-structure">
                    <!-- if 条件 -->
                    <div class="if-block">
                      <div class="condition-header">
                        <span class="condition-label">if 条件</span>
                      </div>
                      <div class="expression-input-container">
                        <a-textarea
                            v-model:value="step.ifCondition"
                            placeholder="请输入if条件表达式"
                            :rows="3"
                            class="expression-input"
                            :status="step.ifValidateStatus"
                            @input="(value) => handleIfConditionInput(index, value)"
                            @focus="(e) => handleIfConditionFocus(e, index)"
                            @blur="() => handleIfConditionBlur(index)"
                        />
                        <!-- 智能提示下拉框 -->
                        <div v-if="showIfSuggestions && activeStepIndex === index && activeConditionType === 'if'"
                             class="epl-suggestions"
                             :style="exprSuggestionStyle">
                          <div v-for="(suggestion, suggestionIndex) in filteredExprSuggestions"
                               :key="suggestion.text"
                               class="suggestion-item"
                               :class="{ active: currentExprSuggestionIndex === suggestionIndex }"
                               @mousedown="selectIfSuggestion(suggestion)"
                          >
                            <span class="suggestion-label">{{ suggestion.label }}</span>
                            <span class="suggestion-type">{{ suggestion.type }}</span>
                          </div>
                        </div>
                        <!-- 验证消息 -->
                        <div class="validation-message">
                          <span :class="['form-tip', step.ifValidateStatus === 'error' ? 'error-tip' : step.ifValidateStatus === 'success' ? 'success-tip' : '']">
                            {{ step.ifValidateMessage || '支持EPL语法，请确保语法正确' }}
                          </span>
                        </div>
                      </div>
                      <a-input v-model:value="step.tvalue" placeholder="请输入true值" class="true-value-input" />
                    </div>

                    <!-- else if 条件列表 -->
                    <div v-for="(elseIf, elseIfIndex) in step.elseIfConditions" :key="elseIfIndex" class="else-if-block">
                      <div class="condition-header">
                        <span class="condition-label">else if 条件 {{ elseIfIndex + 1 }}</span>
                        <a-button
                            type="link"
                            danger
                            size="small"
                            @click="removeElseIfCondition(index, elseIfIndex)"
                        >
                          <delete-outlined />
                        </a-button>
                      </div>
                      <div class="expression-input-container">
                        <a-textarea
                            v-model:value="elseIf.condition"
                            placeholder="请输入else if条件表达式"
                            :rows="3"
                            class="expression-input"
                            :status="elseIf.validateStatus"
                            @input="(value) => handleElseIfConditionInput(index, elseIfIndex, value)"
                            @focus="(e) => handleElseIfConditionFocus(e, index, elseIfIndex)"
                            @blur="() => handleElseIfConditionBlur(index, elseIfIndex)"
                        />
                        <!-- 智能提示下拉框 -->
                        <div v-if="showElseIfSuggestions && activeStepIndex === index && activeConditionType === 'elseIf' && activeElseIfIndex === elseIfIndex"
                             class="epl-suggestions"
                             :style="exprSuggestionStyle">
                          <div v-for="(suggestion, suggestionIndex) in filteredExprSuggestions"
                               :key="suggestion.text"
                               class="suggestion-item"
                               :class="{ active: currentExprSuggestionIndex === suggestionIndex }"
                               @mousedown="selectElseIfSuggestion(suggestion)"
                          >
                            <span class="suggestion-label">{{ suggestion.label }}</span>
                            <span class="suggestion-type">{{ suggestion.type }}</span>
                          </div>
                        </div>
                        <!-- 验证消息 -->
                        <div class="validation-message">
                          <span :class="['form-tip', elseIf.validateStatus === 'error' ? 'error-tip' : elseIf.validateStatus === 'success' ? 'success-tip' : '']">
                            {{ elseIf.validateMessage || '支持EPL语法，请确保语法正确' }}
                          </span>
                        </div>
                      </div>
                      <a-input v-model:value="elseIf.trueValue" placeholder="请输入true值" class="true-value-input" />
                    </div>

                    <!-- else 条件 -->
                    <div class="else-block">
                      <div class="condition-header">
                        <span class="condition-label">else</span>
                      </div>
                      <a-input v-model:value="step.fvalue" placeholder="请输入false值" class="false-value-input" />
                    </div>
                  </div>

                  <!-- 添加else if条件按钮 -->
                  <a-button type="dashed" block @click="addElseIfCondition(index)" class="add-else-if-btn">
                    <plus-outlined />添加else if条件
                  </a-button>
                </div>
              </template>

              <template v-else>
                <a-form-item
                    :name="['ruleCepStepList', index, 'stepMapping']"
                    :rules="[{ required: true, message: '请选择映射字段' }]"
                    label="映射字段"
                >
                  <a-select
                      v-model:value="step.stepMapping"
                      placeholder="请选择映射字段"
                      :options="fieldOptions"
                      show-search
                      :filter-option="(input, option) =>
                      option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
                  />
                </a-form-item>
              </template>
            </a-col>
            <a-col :span="2" class="step-actions">
              <a-button type="link" danger @click="removeStep(index)">
                <delete-outlined />
              </a-button>
            </a-col>
          </a-row>
        </div>
        <a-button type="dashed" block @click="addStep">
          <plus-outlined />添加告警条件
        </a-button>
      <!-- </a-form-item> -->

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="白名单" name="white">
            <a-switch
                v-model:checked="formData.white"
                :checked-value="1"
                :un-checked-value="0"
                checked-children="是"
                un-checked-children="否"
            />
            <template #extra>
              <span class="form-tip">0 正常 1 白名单</span>
            </template>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="异常推送" name="errorStatus">
            <a-switch
                v-model:checked="formData.errorStatus"
                :checked-value="1"
                :un-checked-value="0"
                checked-children="开启"
                un-checked-children="关闭"
            />
            <template #extra>
              <span class="form-tip">0 正常 1 异常推送</span>
            </template>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="日志推送" name="logStatus">
            <a-switch
                v-model:checked="formData.logStatus"
                :checked-value="1"
                :un-checked-value="0"
                checked-children="开启"
                un-checked-children="关闭"
            />
            <template #extra>
              <span class="form-tip">0 正常 1 日志推送</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ formData.id ? '更新' : '创建' }}
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
import { reactive, ref, nextTick, computed, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { cepApi } from '/@/api/business/cep/cep-api';
import { fieldConfigApi } from '/@/api/business/elasticsearch/field-config-api';
import { smartSentry } from '/@/lib/smart-sentry';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

// 定义事件
const emit = defineEmits(['reloadList']);

// 表单引用
const formRef = ref();
const visible = ref(false);
const submitLoading = ref(false);

// 字段配置选项
const fieldOptions = ref([]);

// 获取字段配置
const getFieldConfig = async () => {
  try {
    SmartLoading.show();
    const response = await fieldConfigApi.getFieldList();
    console.log('字段配置原始数据:', response);
    if (response.data) {
      // 将对象转换为数组并处理数据
      fieldOptions.value = Object.values(response.data).map(item => ({
        label: `${item.displayName}(${item.fieldName})`,
        value: item.entityName
      }));
      console.log('处理后的字段选项:', fieldOptions.value);
    }
  } catch (error) {
    smartSentry.captureException(error);
    message.error('获取字段配置失败');
  } finally {
    SmartLoading.hide();
  }
};

// 条件类型选项
const conditionTypes = [
  { label: '静态值', value: 'STATIC' },
  { label: '表达式', value: 'EXPRESSION' },
  { label: '字段映射', value: 'FIELD_MAPPING' }
];

// 过滤选项函数
const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 表单默认值
const defaultFormData = {
  id: null,
  ruleName: '',
  ruleCode: '',
  ruleDescription: '',
  ruleType: '',
  priority: 5,
  status: 'ACTIVE',
  version: '1.0.0',
  epl: '',
  windowSize: null,
  windowSlide: null,
  groups: [], // 数组类型，支持多选
  white: 0, // 修复字段名
  errorStatus: 0,
  logStatus: 1,
  ruleCepStepList: [], // 修复字段名
};

// 表单数据
const formData = reactive({ ...defaultFormData });

// 添加步骤
const addStep = () => {
  formData.ruleCepStepList.push({
    stepName: '',
    eventType: 'STATIC',
    tvalue: '',
    fvalue: '',
    conditionExpression: '',
    stepMapping: '',
    validateStatus: '',
    validateMessage: '',
    // if-else if-else 结构
    ifCondition: '',
    ifValidateStatus: '',
    ifValidateMessage: '',
    elseIfConditions: [],
    conditions: [
      {
        expression: '',
        validateStatus: '',
        validateMessage: ''
      }
    ]
  });
};

// 删除步骤
const removeStep = (index) => {
  formData.ruleCepStepList.splice(index, 1);
};

// EPL编辑器相关
const eplInputRef = ref(null);
const showSuggestions = ref(false);
const currentSuggestionIndex = ref(0);
const suggestionStyle = ref({
  top: '0px',
  left: '0px'
});

// 运算符列表
const operators = [
  { label: '==', value: '==', type: 'operator', description: '等于' },
  { label: '!=', value: '!=', type: 'operator', description: '不等于' },
  { label: '>', value: '>', type: 'operator', description: '大于' },
  { label: '>=', value: '>=', type: 'operator', description: '大于等于' },
  { label: '<', value: '<', type: 'operator', description: '小于' },
  { label: '<=', value: '<=', type: 'operator', description: '小于等于' },
  { label: 'contains', value: 'contains', type: 'operator', description: '包含' }
];

// EPL输入上下文
const eplInputContext = reactive({
  text: '',
  startPos: 0,
  endPos: 0,
  type: null // 'field' | 'operator' | null
});

// 表达式条件输入上下文
const exprInputContext = reactive({
  text: '',
  startPos: 0,
  endPos: 0,
  type: null // 'field' | 'operator' | null
});





// 获取过滤后的EPL建议列表
const filteredSuggestions = computed(() => {
  let suggestions = [];

  // 如果当前类型是运算符且没有输入文本，显示所有运算符
  if (eplInputContext.type === 'operator' && !eplInputContext.text) {
    suggestions = [...operators];
  }
  // 如果有输入文本，根据类型过滤
  else if (eplInputContext.text) {
    if (!eplInputContext.type || eplInputContext.type === 'field') {
      // 添加字段建议
      suggestions = fieldOptions.value.filter(field =>
          field.label.toLowerCase().includes(eplInputContext.text.toLowerCase()) ||
          field.value.toLowerCase().includes(eplInputContext.text.toLowerCase())
      ).map(field => ({
        ...field,
        type: 'field'
      }));
    }

    if (!eplInputContext.type || eplInputContext.type === 'operator') {
      // 添加运算符建议
      const operatorSuggestions = operators.filter(op =>
          op.label.toLowerCase().includes(eplInputContext.text.toLowerCase()) ||
          op.description.toLowerCase().includes(eplInputContext.text.toLowerCase())
      );
      suggestions = [...suggestions, ...operatorSuggestions];
    }
  }
  // 如果既没有类型也没有文本，显示字段建议
  else if (!eplInputContext.type && !eplInputContext.text) {
    suggestions = fieldOptions.value.map(field => ({
      ...field,
      type: 'field'
    }));
  }

  return suggestions;
});



// 选择EPL建议项
const selectSuggestion = (item) => {
  const textarea = eplInputRef.value?.$el.querySelector('textarea');
  if (!textarea) return;

  const before = formData.epl.slice(0, eplInputContext.startPos);
  const after = formData.epl.slice(eplInputContext.endPos);

  // 添加空格并更新文本
  const newValue = item.value + (item.type === 'field' ? ' ' : '');
  formData.epl = before + newValue + after;

  // 设置光标位置并触发新的建议
  nextTick(() => {
    const newPosition = eplInputContext.startPos + newValue.length;
    textarea.setSelectionRange(newPosition, newPosition);
    textarea.focus();

    // 如果选择的是字段，立即显示运算符建议
    if (item.type === 'field') {
      eplInputContext.text = '';
      eplInputContext.type = 'operator';
      eplInputContext.startPos = newPosition;
      eplInputContext.endPos = newPosition;

      // 计算新的下拉框位置
      const { top, left } = getCaretCoordinates(textarea, newPosition);
      suggestionStyle.value = {
        top: `${top + 20}px`,
        left: `${left}px`
      };

      showSuggestions.value = true;
      currentSuggestionIndex.value = 0;
    } else {
      showSuggestions.value = false;
    }
  });
};

// 处理EPL输入
const handleEplInput = (e) => {
  const textarea = eplInputRef.value?.$el.querySelector('textarea');
  if (!textarea) return;

  const cursorPosition = textarea.selectionStart;
  const text = textarea.value;

  // 分析光标位置的上下文
  const beforeCursor = text.slice(0, cursorPosition);
  const words = beforeCursor.split(/\s+/);
  const currentWord = words[words.length - 1];

  if (currentWord) {
    // 更新输入上下文
    eplInputContext.text = currentWord;
    eplInputContext.startPos = cursorPosition - currentWord.length;
    eplInputContext.endPos = cursorPosition;

    // 判断当前输入类型
    const prevWord = words[words.length - 2];
    if (prevWord) {
      // 如果前一个词是运算符，则当前应该输入字段
      if (operators.some(op => op.value === prevWord)) {
        eplInputContext.type = 'field';
      }
      // 如果前一个词是字段，则当前应该输入运算符
      else if (fieldOptions.value.some(field => field.value === prevWord)) {
        eplInputContext.type = 'operator';
      }
      // 其他情况允许输入任何类型
      else {
        eplInputContext.type = null;
      }
    } else {
      // 如果是第一个词，默认为字段输入
      eplInputContext.type = 'field';
    }

    // 计算下拉框位置
    const { top, left } = getCaretCoordinates(textarea, cursorPosition);
    suggestionStyle.value = {
      top: `${top + 20}px`,
      left: `${left}px`
    };

    showSuggestions.value = true;
    currentSuggestionIndex.value = 0;
  } else {
    // 如果当前光标前是空格，且前一个词是字段，显示运算符建议
    const lastWord = words[words.length - 2];
    if (lastWord && fieldOptions.value.some(field => field.value === lastWord)) {
      eplInputContext.text = '';
      eplInputContext.type = 'operator';
      eplInputContext.startPos = cursorPosition;
      eplInputContext.endPos = cursorPosition;

      const { top, left } = getCaretCoordinates(textarea, cursorPosition);
      suggestionStyle.value = {
        top: `${top + 20}px`,
        left: `${left}px`
      };

      showSuggestions.value = true;
      currentSuggestionIndex.value = 0;
    } else {
      showSuggestions.value = false;
    }
  }
};



// 键盘导航
const handleKeyDown = (e) => {
  // EPL建议框键盘导航
  if (showSuggestions.value) {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        currentSuggestionIndex.value = (currentSuggestionIndex.value + 1) % filteredSuggestions.value.length;
        break;
      case 'ArrowUp':
        e.preventDefault();
        currentSuggestionIndex.value = (currentSuggestionIndex.value - 1 + filteredSuggestions.value.length) % filteredSuggestions.value.length;
        break;
      case 'Enter':
        e.preventDefault();
        if (filteredSuggestions.value[currentSuggestionIndex.value]) {
          selectSuggestion(filteredSuggestions.value[currentSuggestionIndex.value]);
        }
        break;
      case 'Escape':
        showSuggestions.value = false;
        break;
    }
  }


};

// 点击外部关闭建议框
const handleClickOutside = (e) => {
  // 关闭EPL建议框
  if (!eplInputRef.value?.$el.contains(e.target)) {
    showSuggestions.value = false;
  }

  // 关闭表达式条件建议框
  const activeTextarea = document.activeElement;
  if (!activeTextarea || !activeTextarea.closest('.expression-input-container')) {
    showExprSuggestions.value = false;
  }

  // 关闭if条件建议框
  if (!activeTextarea || !activeTextarea.closest('.if-block')) {
    showIfSuggestions.value = false;
  }

  // 关闭else if条件建议框
  if (!activeTextarea || !activeTextarea.closest('.else-if-block')) {
    showElseIfSuggestions.value = false;
  }


};

// 在组件挂载时获取字段配置
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown);
  document.addEventListener('click', handleClickOutside);
  document.addEventListener('keydown', handleExprKeyDown);
});

// 清理事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown);
  document.removeEventListener('click', handleClickOutside);
  document.removeEventListener('keydown', handleExprKeyDown);
});

// 添加 EPL 验证状态
const eplValidateStatus = ref('');
const eplValidateMessage = ref('');

// 修改验证函数
const validateEplSyntax = async () => {
  // 如果EPL为空，保持当前状态不变
  if (!formData.epl?.trim()) {
    return true;
  }

  try {
    // 不显示全局loading
    const res = await cepApi.validateEplSyntax(formData.epl);

    if (res.code === 0 || res.ok === true) {
      // 只在状态不同时才更新，避免不必要的重渲染
      if (eplValidateStatus.value !== 'success') {
        eplValidateStatus.value = 'success';
        eplValidateMessage.value = '语法正确';
      }
      return true;
    } else {
      // 只在状态不同时才更新，避免不必要的重渲染
      if (eplValidateStatus.value !== 'error') {
        eplValidateStatus.value = 'error';
        eplValidateMessage.value = res.msg || res.message || '语法错误';
      }
      return false;
    }
  } catch (error) {
    smartSentry.captureError(error);
    // 只在状态不同时才更新，避免不必要的重渲染
    if (eplValidateStatus.value !== 'error') {
      eplValidateStatus.value = 'error';
      eplValidateMessage.value = '验证请求失败';
    }
    return false;
  }
};

// 表达式条件输入相关
const showExprSuggestions = ref(false);
const activeStepIndex = ref(-1);
const activeExprIndex = ref(-1);
const currentExprSuggestionIndex = ref(0);
const exprSuggestionStyle = ref({
  top: '0px',
  left: '0px'
});

// if条件输入相关
const showIfSuggestions = ref(false);
const activeConditionType = ref('');

// else if条件输入相关
const showElseIfSuggestions = ref(false);
const activeElseIfIndex = ref(-1);

// 表达式条件的建议选项 - 包含字段和运算符
const exprSuggestions = [
  // 字段建议会动态添加
  // 比较运算符
  { label: '==', type: '比较运算符', text: '==', description: '等于' },
  { label: '!=', type: '比较运算符', text: '!=', description: '不等于' },
  { label: '>', type: '比较运算符', text: '>', description: '大于' },
  { label: '>=', type: '比较运算符', text: '>=', description: '大于等于' },
  { label: '<', type: '比较运算符', text: '<', description: '小于' },
  { label: '<=', type: '比较运算符', text: '<=', description: '小于等于' },
  // 函数
  { label: 'contains', type: '函数', text: 'contains', description: '包含' },
  { label: 'startsWith', type: '函数', text: 'startsWith', description: '以...开始' },
  { label: 'endsWith', type: '函数', text: 'endsWith', description: '以...结束' },
  { label: 'matches', type: '函数', text: 'matches', description: '匹配正则' },
  // 关键字
  { label: 'in', type: '关键字', text: 'in', description: '在列表中' },
  { label: 'not in', type: '关键字', text: 'not in', description: '不在列表中' },
  { label: 'is null', type: '关键字', text: 'is null', description: '为空' },
  { label: 'is not null', type: '关键字', text: 'is not null', description: '不为空' },
  { label: 'between', type: '关键字', text: 'between', description: '在范围内' },
  // 逻辑运算符
  { label: 'and', type: '逻辑运算符', text: 'and', description: '与' },
  { label: 'or', type: '逻辑运算符', text: 'or', description: '或' },
];

// 过滤后的表达式建议
const filteredExprSuggestions = computed(() => {
  let suggestions = [];

  // 添加字段建议
  let fieldSuggestions = [];
  if (exprInputContext.type === 'field' || exprInputContext.type === null) {
    if (exprInputContext.text) {
      // 有输入内容时，过滤字段
      fieldSuggestions = fieldOptions.value.filter(field =>
          field.label.toLowerCase().includes(exprInputContext.text.toLowerCase()) ||
          field.value.toLowerCase().includes(exprInputContext.text.toLowerCase())
      ).map(field => ({
        label: field.label,
        type: '字段',
        text: field.value,
        description: field.label
      }));
    } else {
      // 没有输入内容时，显示所有字段
      fieldSuggestions = fieldOptions.value.map(field => ({
        label: field.label,
        type: '字段',
        text: field.value,
        description: field.label
      }));
    }
  }

  // 添加运算符建议
  let operatorSuggestions = [];
  if (exprInputContext.type === 'operator' || exprInputContext.type === null) {
    if (exprInputContext.text) {
      // 有输入内容时，过滤运算符
      operatorSuggestions = exprSuggestions.filter(item =>
          item.label.toLowerCase().includes(exprInputContext.text.toLowerCase()) ||
          item.description.toLowerCase().includes(exprInputContext.text.toLowerCase()) ||
          item.type.toLowerCase().includes(exprInputContext.text.toLowerCase())
      );
    } else {
      // 没有输入内容时，显示所有运算符
      operatorSuggestions = [...exprSuggestions];
    }
  }

  suggestions = [...fieldSuggestions, ...operatorSuggestions];

  return suggestions;
});

// 处理表达式条件输入框获得焦点
const handleExprConditionFocus = (e, stepIndex, exprIndex) => {
  activeStepIndex.value = stepIndex;
  activeExprIndex.value = exprIndex;

  // 计算建议框位置
  const textarea = e.target;
  const { top, left } = getCaretCoordinates(textarea, textarea.selectionStart);
  exprSuggestionStyle.value = {
    top: `${top + 24}px`,
    left: `${left}px`
  };

  // 初始化输入上下文
  exprInputContext.text = '';
  exprInputContext.type = 'field';
  exprInputContext.startPos = textarea.selectionStart;
  exprInputContext.endPos = textarea.selectionStart;

  showExprSuggestions.value = true;
  currentExprSuggestionIndex.value = 0;
};

// 处理表达式条件输入框失去焦点
const handleExprConditionBlur = (stepIndex, exprIndex) => {
  setTimeout(() => {
    showExprSuggestions.value = false;
    activeExprIndex.value = -1;
    activeStepIndex.value = -1;

    // 验证表达式语法
    if (stepIndex >= 0 && exprIndex >= 0) {
      validateExprCondition(stepIndex, exprIndex);
    }
  }, 200);
};

// 处理if条件输入框获得焦点
const handleIfConditionFocus = (e, stepIndex) => {
  activeStepIndex.value = stepIndex;
  activeConditionType.value = 'if';

  // 计算建议框位置
  const textarea = e.target;
  const { top, left } = getCaretCoordinates(textarea, textarea.selectionStart);
  exprSuggestionStyle.value = {
    top: `${top + 24}px`,
    left: `${left}px`
  };

  // 初始化输入上下文
  exprInputContext.text = '';
  exprInputContext.type = 'field';
  exprInputContext.startPos = textarea.selectionStart;
  exprInputContext.endPos = textarea.selectionStart;

  showIfSuggestions.value = true;
  currentExprSuggestionIndex.value = 0;
};

// 处理if条件输入框失去焦点
const handleIfConditionBlur = (stepIndex) => {
  setTimeout(() => {
    showIfSuggestions.value = false;
    activeConditionType.value = '';
    activeStepIndex.value = -1;

    // 验证if条件语法
    if (stepIndex >= 0) {
      validateIfCondition(stepIndex);
    }
  }, 200);
};

// 处理if条件输入
const handleIfConditionInput = (stepIndex, value) => {
  const textarea = document.activeElement;
  if (!textarea) return;

  const cursorPosition = textarea.selectionStart;
  const text = textarea.value;

  // 分析光标位置的上下文
  const beforeCursor = text.slice(0, cursorPosition);
  const words = beforeCursor.split(/\s+/);
  const currentWord = words[words.length - 1];

  // 计算下拉框位置
  const { top, left } = getCaretCoordinates(textarea, cursorPosition);
  exprSuggestionStyle.value = {
    top: `${top + 24}px`,
    left: `${left}px`
  };

  if (currentWord) {
    // 更新输入上下文
    exprInputContext.text = currentWord;
    exprInputContext.startPos = cursorPosition - currentWord.length;
    exprInputContext.endPos = cursorPosition;

    // 判断当前输入类型
    const prevWord = words[words.length - 2];
    if (prevWord) {
      // 如果前一个词是运算符，则当前应该输入字段
      if (exprSuggestions.some(op => op.text === prevWord)) {
        exprInputContext.type = 'field';
      }
      // 如果前一个词是字段，则当前应该输入运算符
      else if (fieldOptions.value.some(field => field.value === prevWord)) {
        exprInputContext.type = 'operator';
      }
      // 其他情况允许输入任何类型
      else {
        exprInputContext.type = null;
      }
    } else {
      // 如果是第一个词，默认为字段输入
      exprInputContext.type = 'field';
    }

    showIfSuggestions.value = true;
    currentExprSuggestionIndex.value = 0;
  } else {
    // 如果当前光标前是空格，且前一个词是字段，显示运算符建议
    const lastWord = words[words.length - 2];
    if (lastWord && fieldOptions.value.some(field => field.value === lastWord)) {
      exprInputContext.text = '';
      exprInputContext.type = 'operator';
      exprInputContext.startPos = cursorPosition;
      exprInputContext.endPos = cursorPosition;

      showIfSuggestions.value = true;
      currentExprSuggestionIndex.value = 0;
    } else if (words.length === 1 && !currentWord) {
      // 如果是空输入框，显示所有字段建议
      exprInputContext.text = '';
      exprInputContext.type = 'field';
      exprInputContext.startPos = cursorPosition;
      exprInputContext.endPos = cursorPosition;

      showIfSuggestions.value = true;
      currentExprSuggestionIndex.value = 0;
    } else {
      showIfSuggestions.value = false;
    }
  }
};

// 选择表达式建议
const selectExprSuggestion = (suggestion) => {
  if (activeStepIndex.value >= 0 && activeExprIndex.value >= 0) {
    const step = formData.ruleCepStepList[activeStepIndex.value];
    const condition = step.conditions[activeExprIndex.value];
    const before = condition.expression.slice(0, exprInputContext.startPos);
    const after = condition.expression.slice(exprInputContext.endPos);

    // 添加空格并更新文本
    const newValue = suggestion.text + (suggestion.type === '字段' ? ' ' : '');
    condition.expression = before + newValue + after;

    // 设置光标位置并触发新的建议
    nextTick(() => {
      const textarea = document.activeElement;
      if (textarea) {
        const newPosition = exprInputContext.startPos + newValue.length;
        textarea.setSelectionRange(newPosition, newPosition);
        textarea.focus();

        // 如果选择的是字段，立即显示运算符建议
        if (suggestion.type === '字段') {
          exprInputContext.text = '';
          exprInputContext.type = 'operator';
          exprInputContext.startPos = newPosition;
          exprInputContext.endPos = newPosition;

          // 计算新的下拉框位置
          const { top, left } = getCaretCoordinates(textarea, newPosition);
          exprSuggestionStyle.value = {
            top: `${top + 24}px`,
            left: `${left}px`
          };

          showExprSuggestions.value = true;
          currentExprSuggestionIndex.value = 0;
        } else {
          showExprSuggestions.value = false;
        }
      }
    });
  }
};

// 验证表达式条件语法
const validateExprCondition = async (stepIndex, conditionIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  const condition = step.conditions[conditionIndex];

  // 如果条件为空，保持当前状态不变
  if (!condition.expression?.trim()) {
    return true;
  }

  try {
    // 不显示全局loading
    const res = await cepApi.validateEplSyntax(condition.expression);

    if (res.code === 0 || res.ok === true) {
      // 只在状态不同时才更新，避免不必要的重渲染
      if (condition.validateStatus !== 'success') {
        condition.validateStatus = 'success';
        condition.validateMessage = '语法正确';
      }
      return true;
    } else {
      // 只在状态不同时才更新，避免不必要的重渲染
      if (condition.validateStatus !== 'error') {
        condition.validateStatus = 'error';
        condition.validateMessage = res.msg || res.message || '语法错误';
      }
      return false;
    }
  } catch (error) {
    smartSentry.captureError(error);
    // 只在状态不同时才更新，避免不必要的重渲染
    if (condition.validateStatus !== 'error') {
      condition.validateStatus = 'error';
      condition.validateMessage = '验证请求失败';
    }
    return false;
  }
};

// 验证if条件语法
const validateIfCondition = async (stepIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  if (!step.ifCondition?.trim()) {
    return true;
  }

  try {
    const res = await cepApi.validateEplSyntax(step.ifCondition);
    if (res.code === 0 || res.ok === true) {
      if (step.ifValidateStatus !== 'success') {
        step.ifValidateStatus = 'success';
        step.ifValidateMessage = '语法正确';
      }
      return true;
    } else {
      if (step.ifValidateStatus !== 'error') {
        step.ifValidateStatus = 'error';
        step.ifValidateMessage = res.msg || res.message || '语法错误';
      }
      return false;
    }
  } catch (error) {
    smartSentry.captureError(error);
    if (step.ifValidateStatus !== 'error') {
      step.ifValidateStatus = 'error';
      step.ifValidateMessage = '验证请求失败';
    }
    return false;
  }
};

// 处理else if条件输入框获得焦点
const handleElseIfConditionFocus = (e, stepIndex, elseIfIndex) => {
  activeStepIndex.value = stepIndex;
  activeConditionType.value = 'elseIf';
  activeElseIfIndex.value = elseIfIndex;

  // 计算建议框位置
  const textarea = e.target;
  const { top, left } = getCaretCoordinates(textarea, textarea.selectionStart);
  exprSuggestionStyle.value = {
    top: `${top + 24}px`,
    left: `${left}px`
  };

  // 初始化输入上下文
  exprInputContext.text = '';
  exprInputContext.type = 'field';
  exprInputContext.startPos = textarea.selectionStart;
  exprInputContext.endPos = textarea.selectionStart;

  showElseIfSuggestions.value = true;
  currentExprSuggestionIndex.value = 0;
};

// 处理else if条件输入框失去焦点
const handleElseIfConditionBlur = (stepIndex, elseIfIndex) => {
  setTimeout(() => {
    showElseIfSuggestions.value = false;
    activeConditionType.value = '';
    activeElseIfIndex.value = -1;
    activeStepIndex.value = -1;

    // 验证else if条件语法
    if (stepIndex >= 0 && elseIfIndex >= 0) {
      validateElseIfCondition(stepIndex, elseIfIndex);
    }
  }, 200);
};

// 处理else if条件输入
const handleElseIfConditionInput = (stepIndex, elseIfIndex, value) => {
  const textarea = document.activeElement;
  if (!textarea) return;

  const cursorPosition = textarea.selectionStart;
  const text = textarea.value;

  // 分析光标位置的上下文
  const beforeCursor = text.slice(0, cursorPosition);
  const words = beforeCursor.split(/\s+/);
  const currentWord = words[words.length - 1];

  // 计算下拉框位置
  const { top, left } = getCaretCoordinates(textarea, cursorPosition);
  exprSuggestionStyle.value = {
    top: `${top + 24}px`,
    left: `${left}px`
  };

  if (currentWord) {
    // 更新输入上下文
    exprInputContext.text = currentWord;
    exprInputContext.startPos = cursorPosition - currentWord.length;
    exprInputContext.endPos = cursorPosition;

    // 判断当前输入类型
    const prevWord = words[words.length - 2];
    if (prevWord) {
      // 如果前一个词是运算符，则当前应该输入字段
      if (exprSuggestions.some(op => op.text === prevWord)) {
        exprInputContext.type = 'field';
      }
      // 如果前一个词是字段，则当前应该输入运算符
      else if (fieldOptions.value.some(field => field.value === prevWord)) {
        exprInputContext.type = 'operator';
      }
      // 其他情况允许输入任何类型
      else {
        exprInputContext.type = null;
      }
    } else {
      // 如果是第一个词，默认为字段输入
      exprInputContext.type = 'field';
    }

    showElseIfSuggestions.value = true;
    currentExprSuggestionIndex.value = 0;
  } else {
    // 如果当前光标前是空格，且前一个词是字段，显示运算符建议
    const lastWord = words[words.length - 2];
    if (lastWord && fieldOptions.value.some(field => field.value === lastWord)) {
      exprInputContext.text = '';
      exprInputContext.type = 'operator';
      exprInputContext.startPos = cursorPosition;
      exprInputContext.endPos = cursorPosition;

      showElseIfSuggestions.value = true;
      currentExprSuggestionIndex.value = 0;
    } else if (words.length === 1 && !currentWord) {
      // 如果是空输入框，显示所有字段建议
      exprInputContext.text = '';
      exprInputContext.type = 'field';
      exprInputContext.startPos = cursorPosition;
      exprInputContext.endPos = cursorPosition;

      showElseIfSuggestions.value = true;
      currentExprSuggestionIndex.value = 0;
    } else {
      showElseIfSuggestions.value = false;
    }
  }
};

// 验证else if条件语法
const validateElseIfCondition = async (stepIndex, elseIfIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  const elseIf = step.elseIfConditions[elseIfIndex];

  if (!elseIf.condition?.trim()) {
    return true;
  }

  try {
    const res = await cepApi.validateEplSyntax(elseIf.condition);
    if (res.code === 0 || res.ok === true) {
      if (elseIf.validateStatus !== 'success') {
        elseIf.validateStatus = 'success';
        elseIf.validateMessage = '语法正确';
      }
      return true;
    } else {
      if (elseIf.validateStatus !== 'error') {
        elseIf.validateStatus = 'error';
        elseIf.validateMessage = res.msg || res.message || '语法错误';
      }
      return false;
    }
  } catch (error) {
    smartSentry.captureError(error);
    if (elseIf.validateStatus !== 'error') {
      elseIf.validateStatus = 'error';
      elseIf.validateMessage = '验证请求失败';
    }
    return false;
  }
};

// 添加键盘事件处理
const handleExprKeyDown = (e) => {
  if (!showExprSuggestions.value && !showIfSuggestions.value && !showElseIfSuggestions.value) return;

  let currentSuggestions = [];
  let currentIndex = 0;
  let showSuggestions = false;

  if (showExprSuggestions.value) {
    currentSuggestions = filteredExprSuggestions.value;
    currentIndex = currentExprSuggestionIndex.value;
    showSuggestions = showExprSuggestions;
  } else if (showIfSuggestions.value) {
    currentSuggestions = filteredExprSuggestions.value;
    currentIndex = currentExprSuggestionIndex.value;
    showSuggestions = showIfSuggestions;
  } else if (showElseIfSuggestions.value) {
    currentSuggestions = filteredExprSuggestions.value;
    currentIndex = currentExprSuggestionIndex.value;
    showSuggestions = showElseIfSuggestions;
  }

  switch (e.key) {
    case 'ArrowDown':
      e.preventDefault();
      currentExprSuggestionIndex.value = (currentIndex + 1) % currentSuggestions.length;
      break;
    case 'ArrowUp':
      e.preventDefault();
      currentExprSuggestionIndex.value = (currentIndex - 1 + currentSuggestions.length) % currentSuggestions.length;
      break;
    case 'Enter':
      e.preventDefault();
      if (currentSuggestions[currentIndex]) {
        if (showExprSuggestions.value) {
          selectExprSuggestion(currentSuggestions[currentIndex]);
        } else if (showIfSuggestions.value) {
          selectIfSuggestion(currentSuggestions[currentIndex]);
        } else if (showElseIfSuggestions.value) {
          selectElseIfSuggestion(currentSuggestions[currentIndex]);
        }
      }
      break;
    case 'Escape':
      showSuggestions.value = false;
      break;
  }
};

// 添加条件表达式
const addCondition = (stepIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  step.conditions.push({
    expression: '',
    validateStatus: '',
    validateMessage: ''
  });
};

// 删除条件表达式
const removeCondition = (stepIndex, conditionIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  step.conditions.splice(conditionIndex, 1);
};

// 添加else if条件
const addElseIfCondition = (stepIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  step.elseIfConditions.push({
    condition: '',
    trueValue: '',
    validateStatus: '',
    validateMessage: ''
  });
};

// 删除else if条件
const removeElseIfCondition = (stepIndex, elseIfIndex) => {
  const step = formData.ruleCepStepList[stepIndex];
  step.elseIfConditions.splice(elseIfIndex, 1);
};


// 表单验证规则
const rules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 100, message: '规则名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  ruleCode: [
    { required: true, message: '请输入规则编码', trigger: 'blur' },
    { min: 2, max: 50, message: '规则编码长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '规则编码只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  ruleType: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { type: 'number', min: 1, message: '优先级必须大于等于1', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择规则状态', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^[0-9]+\.[0-9]+(\.[0-9]+)?$/, message: '版本号格式不正确，如：1.0.0', trigger: 'blur' }
  ],
  epl: [
    { required: true, message: '请输入规则语句' }
    // 移除语法验证规则
  ],
  ruleCepStepList: [
    {
      validator: async (_, value) => {
        // 移除验证逻辑，直接返回成功
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ]
};

// 显示表单
const show = async (data = null) => {
  try {
    // 重置表单
    Object.assign(formData, defaultFormData);

    // 设置弹窗可见
    visible.value = true;

    // 获取字段配置
    await getFieldConfig();

    // 如果是编辑模式，获取详情数据
    if (data && data.id) {
      try {
        SmartLoading.show();
        const response = await cepApi.detail(data.id);
        const detailData = response.data;

        // 处理ruleCepStepList数据，将多个相同stepOrder的表达式条件合并为if-else if-else结构
        if (detailData.ruleCepStepList && detailData.ruleCepStepList.length > 0) {
          console.log('原始ruleCepStepList数据:', detailData.ruleCepStepList);
          
          const processedStepList = [];
          const stepOrderGroups = {};

          // 按stepOrder分组
          detailData.ruleCepStepList.forEach(step => {
            if (!stepOrderGroups[step.stepOrder]) {
              stepOrderGroups[step.stepOrder] = [];
            }
            stepOrderGroups[step.stepOrder].push(step);
          });

          console.log('按stepOrder分组后的数据:', stepOrderGroups);

          // 处理每个stepOrder组
          Object.keys(stepOrderGroups).sort((a, b) => parseInt(a) - parseInt(b)).forEach(stepOrder => {
            const steps = stepOrderGroups[stepOrder];
            console.log(`处理stepOrder ${stepOrder} 的步骤:`, steps);

            if (steps.length === 1) {
              // 单个条件，直接添加
              const step = steps[0];
              if (step.eventType === 'EXPRESSION') {
                // 表达式模式，转换为if-else if-else结构
                processedStepList.push({
                  stepName: step.stepName,
                  eventType: 'EXPRESSION',
                  tvalue: step.tvalue || '',
                  fvalue: step.fvalue || '',
                  stepMapping: step.stepMapping || '',
                  validateStatus: step.validateStatus || '',
                  validateMessage: step.validateMessage || '',
                  // if-else if-else 结构
                  ifCondition: step.conditionExpression || '',
                  ifValidateStatus: step.validateStatus || '',
                  ifValidateMessage: step.validateMessage || '',
                  elseIfConditions: [],
                  conditions: [
                    {
                      expression: step.conditionExpression || '',
                      validateStatus: step.validateStatus || '',
                      validateMessage: step.validateMessage || ''
                    }
                  ]
                });
              } else {
                // 非表达式模式，直接添加
                processedStepList.push({
                  ...step,
                  // 初始化if-else if-else结构
                  ifCondition: '',
                  ifValidateStatus: '',
                  ifValidateMessage: '',
                  elseIfConditions: [],
                  conditions: [
                    {
                      expression: step.conditionExpression || '',
                      validateStatus: step.validateStatus || '',
                      validateMessage: step.validateMessage || ''
                    }
                  ]
                });
              }
            } else {
              // 多个条件，合并为if-else if-else结构
              const firstStep = steps[0];
              const expressionSteps = steps.filter(s => s.eventType === 'EXPRESSION' && s.conditionExpression);
              const nonExpressionSteps = steps.filter(s => s.eventType !== 'EXPRESSION' || !s.conditionExpression);

              console.log('表达式步骤:', expressionSteps);
              console.log('非表达式步骤:', nonExpressionSteps);

              if (expressionSteps.length > 0) {
                const ifStep = expressionSteps[0];
                const elseIfSteps = expressionSteps.slice(1);
                // 查找else条件（没有conditionExpression的步骤）
                const elseStep = nonExpressionSteps.find(s => !s.conditionExpression || s.conditionExpression.trim() === '');

                console.log('if步骤:', ifStep);
                console.log('else if步骤:', elseIfSteps);
                console.log('else步骤:', elseStep);

                processedStepList.push({
                  stepName: firstStep.stepName,
                  eventType: 'EXPRESSION',
                  tvalue: ifStep.tvalue || '',
                  fvalue: ifStep.fvalue || '', // 使用ifStep的fvalue作为默认的else值
                  stepMapping: firstStep.stepMapping || '',
                  validateStatus: '',
                  validateMessage: '',
                  // if-else if-else 结构
                  ifCondition: ifStep.conditionExpression || '',
                  ifValidateStatus: ifStep.validateStatus || '',
                  ifValidateMessage: ifStep.validateMessage || '',
                  elseIfConditions: elseIfSteps.map(step => ({
                    condition: step.conditionExpression || '',
                    trueValue: step.tvalue || '',
                    validateStatus: step.validateStatus || '',
                    validateMessage: step.validateMessage || ''
                  })),
                  conditions: [
                    {
                      expression: ifStep.conditionExpression || '',
                      validateStatus: ifStep.validateStatus || '',
                      validateMessage: ifStep.validateMessage || ''
                    }
                  ]
                });
              } else if (nonExpressionSteps.length > 0) {
                // 没有表达式条件，但有非表达式条件（可能是else条件）
                const firstNonExpressionStep = nonExpressionSteps[0];
                processedStepList.push({
                  stepName: firstStep.stepName,
                  eventType: firstNonExpressionStep.eventType,
                  tvalue: firstNonExpressionStep.tvalue || '',
                  fvalue: firstNonExpressionStep.fvalue || '',
                  stepMapping: firstNonExpressionStep.stepMapping || '',
                  validateStatus: firstNonExpressionStep.validateStatus || '',
                  validateMessage: firstNonExpressionStep.validateMessage || '',
                  // 初始化if-else if-else结构
                  ifCondition: '',
                  ifValidateStatus: '',
                  ifValidateMessage: '',
                  elseIfConditions: [],
                  conditions: [
                    {
                      expression: firstNonExpressionStep.conditionExpression || '',
                      validateStatus: firstNonExpressionStep.validateStatus || '',
                      validateMessage: firstNonExpressionStep.validateMessage || ''
                    }
                  ]
                });
              } else {
                // 没有表达式条件，直接添加第一个
                processedStepList.push({
                  ...firstStep,
                  // 初始化if-else if-else结构
                  ifCondition: '',
                  ifValidateStatus: '',
                  ifValidateMessage: '',
                  elseIfConditions: [],
                  conditions: [
                    {
                      expression: firstStep.conditionExpression || '',
                      validateStatus: firstStep.validateStatus || '',
                      validateMessage: firstStep.validateMessage || ''
                    }
                  ]
                });
              }
            }
          });

          console.log('处理后的ruleCepStepList数据:', processedStepList);
          detailData.ruleCepStepList = processedStepList;
        }

        // 处理groups字段：将逗号分隔的字符串转换为数组
        if (detailData.groups && typeof detailData.groups === 'string') {
          detailData.groups = detailData.groups.split(',').filter(item => item.trim());
        } else if (!detailData.groups) {
          detailData.groups = [];
        }

        Object.assign(formData, detailData);
      } catch (error) {
        smartSentry.captureException(error);
        message.error('获取规则详情失败');
        return;
      } finally {
        SmartLoading.hide();
      }
    }

    // 等待DOM更新后清除表单验证状态（不清除数据）
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    });
  } catch (error) {
    smartSentry.captureException(error);
    message.error('打开表单失败');
  }
};

// 调试函数：查看数据组装过程
const debugDataAssembly = (originalData, processedData) => {
  console.log('=== 数据组装调试信息 ===');
  console.log('原始表单数据:', originalData);
  console.log('处理后的数据:', processedData);
  console.log('ruleCepStepList 变化:');
  console.log('原始:', originalData.ruleCepStepList);
  console.log('处理后:', processedData.ruleCepStepList);
  console.log('=== 调试信息结束 ===');
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate();

    submitLoading.value = true;
    SmartLoading.show();

    // 组装数据 - 处理表达式模式的if-else if-else结构
    const processedData = { ...formData };
    const processedStepList = [];
    let stepOrder = 1;

    for (let i = 0; i < formData.ruleCepStepList.length; i++) {
      const step = formData.ruleCepStepList[i];

      if (step.eventType === 'EXPRESSION') {
        // 表达式模式：将if-else if-else结构解析成多个ruleCepStep实体

        // 处理if条件
        if (step.ifCondition && step.ifCondition.trim()) {
          processedStepList.push({
            stepName: step.stepName,
            eventType: 'EXPRESSION',
            stepOrder: stepOrder,
            tvalue: step.tvalue || '',
            fvalue: step.fvalue || '', // 所有条件都使用相同的fvalue
            conditionExpression: step.ifCondition.trim(),
            stepMapping: '',
            validateStatus: '', // 移除验证状态
            validateMessage: '' // 移除验证消息
          });
        }

        // 处理else if条件
        if (step.elseIfConditions && step.elseIfConditions.length > 0) {
          for (const elseIf of step.elseIfConditions) {
            if (elseIf.condition && elseIf.condition.trim()) {
              processedStepList.push({
                stepName: step.stepName,
                eventType: 'EXPRESSION',
                stepOrder: stepOrder,
                tvalue: elseIf.trueValue || '',
                fvalue: step.fvalue || '', // 所有条件都使用相同的fvalue
                conditionExpression: elseIf.condition.trim(),
                stepMapping: '',
                validateStatus: '', // 移除验证状态
                validateMessage: '' // 移除验证消息
              });
            }
          }
        }

        // 如果有fvalue但没有if和else if条件，创建一个默认的else条件
        if (step.fvalue && 
            (!step.ifCondition || !step.ifCondition.trim()) &&
            (!step.elseIfConditions || step.elseIfConditions.length === 0)) {
          processedStepList.push({
            stepName: step.stepName,
            eventType: 'EXPRESSION',
            stepOrder: stepOrder,
            tvalue: '',
            fvalue: step.fvalue,
            conditionExpression: '', // else条件不需要表达式
            stepMapping: '',
            validateStatus: '', // 移除验证状态
            validateMessage: '' // 移除验证消息
          });
        }

        stepOrder++;
      } else {
        // 非表达式模式：直接添加
        processedStepList.push({
          ...step,
          stepOrder: stepOrder,
          validateStatus: '', // 移除验证状态
          validateMessage: '' // 移除验证消息
        });
        stepOrder++;
      }
    }

    // 更新处理后的数据
    processedData.ruleCepStepList = processedStepList;

    // 处理groups字段：将数组转换为逗号分隔的字符串
    if (Array.isArray(processedData.groups)) {
      processedData.groups = processedData.groups.join(',');
    }

    // 调试信息
    debugDataAssembly(formData, processedData);

    let result;
    if (formData.id) {
      // 更新
      result = await cepApi.update(processedData);
      message.success('规则更新成功');
    } else {
      // 新增
      result = await cepApi.add(processedData);
      message.success('规则创建成功');
    }

    // 检查API调用是否成功
    if (result && (result.code === 0 || result.ok === true)) {
      visible.value = false;
      emit('reloadList');
    } else {
      // API返回失败状态
      const errorMsg = result?.msg || result?.message || '操作失败';
      message.error(errorMsg);
    }
  } catch (error) {
    if (error.errorFields) {
      // 表单验证失败
      message.error('请检查表单填写是否正确');
    } else {
      // API调用失败
      smartSentry.captureException(error);
      message.error(formData.id ? '规则更新失败' : '规则创建失败');
    }
  } finally {
    submitLoading.value = false;
    SmartLoading.hide();
  }
};

// 取消操作
const handleCancel = () => {
  visible.value = false;
  Object.assign(formData, defaultFormData);
};

// 暴露方法给父组件
defineExpose({
  show
});

// 获取光标坐标的辅助函数
function getCaretCoordinates(element, position) {
  const { offsetLeft, offsetTop } = element;
  const { lineHeight } = getComputedStyle(element);

  // 创建临时元素计算位置
  const div = document.createElement('div');
  div.style.cssText = getComputedStyle(element).cssText;
  div.style.height = 'auto';
  div.style.position = 'absolute';
  div.style.visibility = 'hidden';
  div.style.whiteSpace = 'pre-wrap';

  const textBeforeCursor = element.value.substring(0, position);
  div.textContent = textBeforeCursor;
  document.body.appendChild(div);

  const lines = Math.floor(div.offsetHeight / parseInt(lineHeight));
  const left = offsetLeft + (div.offsetWidth % element.offsetWidth);
  const top = offsetTop + (lines * parseInt(lineHeight));

  document.body.removeChild(div);

  return { top, left };
}

// 选择if条件建议
const selectIfSuggestion = (suggestion) => {
  if (activeStepIndex.value >= 0 && activeConditionType.value === 'if') {
    const step = formData.ruleCepStepList[activeStepIndex.value];
    const before = step.ifCondition.slice(0, exprInputContext.startPos);
    const after = step.ifCondition.slice(exprInputContext.endPos);

    // 添加空格并更新文本
    const newValue = suggestion.text + (suggestion.type === '字段' ? ' ' : '');
    step.ifCondition = before + newValue + after;

    // 设置光标位置并触发新的建议
    nextTick(() => {
      const textarea = document.activeElement;
      if (textarea) {
        const newPosition = exprInputContext.startPos + newValue.length;
        textarea.setSelectionRange(newPosition, newPosition);
        textarea.focus();

        // 如果选择的是字段，立即显示运算符建议
        if (suggestion.type === '字段') {
          exprInputContext.text = '';
          exprInputContext.type = 'operator';
          exprInputContext.startPos = newPosition;
          exprInputContext.endPos = newPosition;

          // 计算新的下拉框位置
          const { top, left } = getCaretCoordinates(textarea, newPosition);
          exprSuggestionStyle.value = {
            top: `${top + 24}px`,
            left: `${left}px`
          };

          showIfSuggestions.value = true;
          currentExprSuggestionIndex.value = 0;
        } else {
          showIfSuggestions.value = false;
        }
      }
    });
  }
};

// 选择else if条件建议
const selectElseIfSuggestion = (suggestion) => {
  if (activeStepIndex.value >= 0 && activeConditionType.value === 'elseIf' && activeElseIfIndex.value >= 0) {
    const step = formData.ruleCepStepList[activeStepIndex.value];
    const elseIf = step.elseIfConditions[activeElseIfIndex.value];
    const before = elseIf.condition.slice(0, exprInputContext.startPos);
    const after = elseIf.condition.slice(exprInputContext.endPos);

    // 添加空格并更新文本
    const newValue = suggestion.text + (suggestion.type === '字段' ? ' ' : '');
    elseIf.condition = before + newValue + after;

    // 设置光标位置并触发新的建议
    nextTick(() => {
      const textarea = document.activeElement;
      if (textarea) {
        const newPosition = exprInputContext.startPos + newValue.length;
        textarea.setSelectionRange(newPosition, newPosition);
        textarea.focus();

        // 如果选择的是字段，立即显示运算符建议
        if (suggestion.type === '字段') {
          exprInputContext.text = '';
          exprInputContext.type = 'operator';
          exprInputContext.startPos = newPosition;
          exprInputContext.endPos = newPosition;

          // 计算新的下拉框位置
          const { top, left } = getCaretCoordinates(textarea, newPosition);
          exprSuggestionStyle.value = {
            top: `${top + 24}px`,
            left: `${left}px`
          };

          showElseIfSuggestions.value = true;
          currentExprSuggestionIndex.value = 0;
        } else {
          showElseIfSuggestions.value = false;
        }
      }
    });
  }
};
</script>

<style scoped lang="less">
.form-tip {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  transition: color 0.3s ease;  // 添加颜色过渡动画

  &.error-tip {
    color: #ff4d4f;
  }

  &.success-tip {
    color: #52c41a;
  }
}

:deep(.ant-form-item-extra) {
  margin-top: 4px;
}

:deep(.ant-divider) {
  margin: 28px 0 20px 0;
  font-weight: 600;
  font-size: 16px;

  &::before,
  &::after {
    border-top-color: rgba(0, 0, 0, 0.06);
  }
}

:deep(.ant-form-item) {
  margin-bottom: 16px;

  .ant-form-item-label > label {
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
  }
}

:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-switch) {
  min-width: 60px;
}

.step-item {
  position: relative;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s;

  &:hover {
    border-color: #40a9ff;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}

.step-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

:deep(.ant-select) {
  width: 100%;
}

.expression-container {
  padding: 12px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.expression-item {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    border-color: #40a9ff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  &:last-child {
    margin-bottom: 12px;
  }
}

.expression-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;

  span {
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
  }
}

.expression-input {
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }
}

.else-block {
  background: #fafafa;
  border-style: dashed;
}

.add-expression-btn {
  margin-top: 12px;
  border-style: dashed;

  &:hover {
    color: #40a9ff;
    border-color: #40a9ff;
  }
}

.add-condition-btn {
  margin-top: 12px;
  border-style: dashed;

  &:hover {
    color: #40a9ff;
    border-color: #40a9ff;
  }
}

.add-else-if-btn {
  margin-top: 12px;
  border-style: dashed;

  &:hover {
    color: #40a9ff;
    border-color: #40a9ff;
  }
}

.if-else-structure {
  .if-block,
  .else-if-block,
  .else-block {
    margin-bottom: 16px;
    padding: 16px;
    background: #fff;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      border-color: #40a9ff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
  }

  .if-block {
    border-left: 4px solid #52c41a;
  }

  .else-if-block {
    border-left: 4px solid #1890ff;
  }

  .else-block {
    border-left: 4px solid #faad14;
    background: #fafafa;
  }
}

.condition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;

  .condition-label {
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
  }
}

.true-value-input,
.false-value-input {
  margin-top: 12px;
}

// 添加动画效果
.step-item,
.expression-item {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.epl-editor {
  position: relative;
}

.epl-suggestions {
  position: absolute;
  z-index: 1000;
  max-height: 200px;
  min-width: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;

  &:hover,
  &.active {
    background: #e6f7ff;
  }

  .suggestion-label {
    color: rgba(0, 0, 0, 0.85);
  }

  .suggestion-type {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 2px;
  }
}

.expression-input-container {
  position: relative;
  margin-bottom: 8px;
}

.expression-input {
  width: 100%;
  margin-bottom: 12px;

  &:focus {
    border-color: #40a9ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }
}

.expression-input-container {
  position: relative;
  margin-bottom: 8px;
}

.expression-item {
  .ant-form-item-extra {
    margin-top: 4px;
  }
}

:deep(.ant-input-status-error) {
  border-color: #ff4d4f;
}

:deep(.ant-input-status-success) {
  border-color: #52c41a;
}

:deep(.ant-textarea-status-error) {
  border-color: #ff4d4f;
}

:deep(.ant-textarea-status-success) {
  border-color: #52c41a;
}


</style>
